/*
 * Powered By fanrenqij.com
 * Since 2017 - 2017
 */

package com.fanrenqiji.modules.business.messagetemplate.web;


import com.fanrenqiji.common.config.GlobalSetting;
import com.fanrenqiji.common.persistence.Page;
import com.fanrenqiji.common.utils.DateUtils;
import com.fanrenqiji.common.utils.FreeMarkerUtils;
import com.fanrenqiji.common.web.BaseController;
import com.fanrenqiji.entity.MessageTemplateEntity;
/*import com.fanrenqiji.modules.business.campperiod.service.CampPeriodService;
import com.fanrenqiji.modules.business.campperiod.vo.CampPeriodVO;
import com.fanrenqiji.modules.business.classroom.service.ClassRoomService;
import com.fanrenqiji.modules.business.classroom.vo.ClassRoomVO;*/
import com.fanrenqiji.modules.business.messagequeue.service.MessageQueueService;
import com.fanrenqiji.modules.business.messagequeue.vo.MessageQueueVO;
import com.fanrenqiji.modules.business.messagerecord.service.MessageRecordService;
import com.fanrenqiji.modules.business.messagerecord.vo.MessageRecordVO;
import com.fanrenqiji.modules.business.parent.service.ParentService;
import com.fanrenqiji.modules.business.parent.vo.ParentVO;
/*import com.fanrenqiji.modules.business.student.service.StudentService;
import com.fanrenqiji.modules.business.student.vo.StudentVO;*/
import com.fanrenqiji.modules.sys.utils.UserUtils;
import com.sun.javafx.sg.prism.NGShape;
import freemarker.template.TemplateException;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import com.fanrenqiji.modules.business.messagetemplate.vo.MessageTemplateVO;
import com.fanrenqiji.modules.business.messagetemplate.service.MessageTemplateService;

@Controller
@RequestMapping(value = "${adminPath}/business/messagetemplate")
public class MessageTemplateController extends BaseController {

    private static Logger log = LoggerFactory.getLogger(MessageTemplateController.class);
    @Autowired
    private MessageTemplateService messageTemplateService;
    @Autowired
    private ParentService parentService;
    @Autowired
    private MessageQueueService messageQueueService;
    @Autowired
    private MessageRecordService messageRecordService;


    @ModelAttribute("messageTemplate")
    public MessageTemplateVO getMessageTemplate(@RequestParam(required = false) String id) {
        if (StringUtils.isNotEmpty(id)) {
            return messageTemplateService.get(id);
        } else {
            return new MessageTemplateVO();
        }
    }

    /**
     * 列表
     *
     * @return
     */
    @RequiresPermissions("business:messagetemplate:view")
    @RequestMapping(value = {"list", ""})
    public String list(MessageTemplateVO messageTemplate, HttpServletRequest request,
                       HttpServletResponse response, Model model) {
        Page<MessageTemplateVO> page = messageTemplateService.findMessageTemplateByPage(new Page<MessageTemplateVO>(request, response),
                messageTemplate);
        model.addAttribute("page", page);
        model.addAttribute("messageTemplate", messageTemplate);
        return "modules/business/messagetemplate/messagetemplateList";
    }

    /**
     * 选择列表
     *
     * @return
     */
    @RequestMapping(value = "select")
    public String select(MessageTemplateVO messageTemplate, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<MessageTemplateVO> page = messageTemplateService.findMessageTemplateByPage(new Page<MessageTemplateVO>(request, response, 10), messageTemplate);
        model.addAttribute("page", page);
        model.addAttribute("messageTemplate", messageTemplate);
        return "modules/business/messagetemplate/messagetemplateSelect";
    }

    /**
     * 用户添加更新表
     *
     * @param model
     * @return
     */
    @RequiresPermissions("business:messagetemplate:view")
    @RequestMapping(value = "form")
    public String form(Model model, MessageTemplateVO messageTemplate) {
        if (StringUtils.isNotEmpty(messageTemplate.getId())) {
            model.addAttribute("messageTemplate", messageTemplateService.get(messageTemplate.getId()));
        } else {
            model.addAttribute("messageTemplate", messageTemplate);
        }
        return "modules/business/messagetemplate/messagetemplateForm";
    }

    /**
     * 查看
     *
     * @param model
     * @return
     */
    @RequiresPermissions("business:messagetemplate:view")
    @RequestMapping(value = "look")
    public String look(Model model, MessageTemplateVO messageTemplate) {
        if (StringUtils.isNotEmpty(messageTemplate.getId())) {
            model.addAttribute("messageTemplate", messageTemplateService.get(messageTemplate.getId()));
        }
        return "modules/business/messagetemplate/messagetemplateLook";
    }

    /**
     * 添加或修改提交
     *
     * @param messageTemplate
     * @param model
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("business:messagetemplate:edit")
    @RequestMapping(value = "save")
    public String save(MessageTemplateVO messageTemplate, Model model,
                       RedirectAttributes redirectAttributes) {// TODO @Valid 添加后端校验
        if (!beanValidator(model, messageTemplate)) {
            return form(model, messageTemplate);
        }
        messageTemplateService.update(messageTemplate);
        addMessage(redirectAttributes, "保存成功");
        return "redirect:" + GlobalSetting.getAdminPath()
                + "/business/messagetemplate/?repage";
    }

    /**
     * 删除操作
     *
     * @return
     */
    @RequestMapping("delete")
    @RequiresPermissions("business:messagetemplate:edit")
    public String delete(String id, RedirectAttributes redirectAttributes) {
        messageTemplateService.delete(id);
        addMessage(redirectAttributes, "删除成功");
        return "redirect:" + GlobalSetting.getAdminPath() + "/business/messagetemplate/";
    }

    /**
     * 发送消息 视图跳转 弹窗形式
     * @param classroomId
     * @param campperiodId
     * @param model
     * @return
     */
    @RequestMapping("sendMassage")
    @RequiresPermissions("business:messagetemplate:sendMassage")
    public String sendMassage(String classroomId,String campperiodId,String returnUrl,Model model) {
        /*String target="";
        if (classroomId!=null){
            ClassRoomVO vo = classRoomService.get(classroomId);
            target=vo.getName()+"("+studentService.getStudentNumByClass(classroomId)+"人)";
        }
        if (campperiodId!=null){
            CampPeriodVO vo = campPeriodService.get(campperiodId);
            target=vo.getName()+"("+studentService.getStudentNumByCampperiod(campperiodId)+"人)";
        }
        if (!target.equals("")) model.addAttribute("target",target);
        model.addAttribute("classroomId",classroomId);
        model.addAttribute("campperiodId",campperiodId);
        model.addAttribute("returnUrl",returnUrl);*/
        return "modules/business/messagetemplate/sendMassage";
    }

    /**
     *
     * @param returnUrl  /business/messagetemplate/
     * @param classroomId  目标  班级
     * @param campperiodId 目标营期
     * @param messagetemplateId 模版id
     * @param templateContent 模版内容
     * @param type              发送类型 0短信  1微信
     * @param model
     * @param redirectAttributes
     * @return
     */
    @RequestMapping("sendmsgbycamporclass")
    @RequiresPermissions("business:messagetemplate:sendMassage")
    public String sendMsgByCampOrClass(String returnUrl,String classroomId,String campperiodId,String messagetemplateId,
                        String type ,String templateContent,Model model,RedirectAttributes redirectAttributes){
      /*  List<StudentVO> studentList=null;
        MessageTemplateVO messageTemplateVO = messageTemplateService.get(messagetemplateId);
        String Content=messageTemplateVO.getEditable()==1?templateContent:messageTemplateVO.getTemplateContent().toString();//通知模版
        if (StringUtils.isNotEmpty(classroomId)||StringUtils.isNotEmpty(campperiodId)){
            //符合规则 准备数据
            StudentVO studentVO=new StudentVO();
            if (StringUtils.isNotEmpty(classroomId)) studentVO.setClassRoomId(classroomId); //班级通知
            if (StringUtils.isNotEmpty(campperiodId)) studentVO.setCampPeriodId(campperiodId);//营期通知
            studentList=studentService.getList(studentVO);//需要发送通知的学生列表
            for (StudentVO vo : studentList) {
                try {
                        ParentVO parentVO =vo.getParent();
                        Map<String,Object> map= new HashMap();
                        map.put("studentName",vo.getName());
                        map.put("parentName",parentVO.getName());
                        map.put("classRoomName",vo.getClassRoom().getName());
                        map.put("teacherName",vo.getClassRoom().getTeacher());
                        map.put("userName", UserUtils.getUser().getName());
                        map.put("dateTime", DateUtils.getDateTime());
                        map.put("templateId",messageTemplateVO.getWeChatTemplateId());
                        if (StringUtils.isNotBlank(messageTemplateVO.getAttributeName())) {
                            map.put(messageTemplateVO.getAttributeName(), messageTemplateVO.getAttributeValue());
                        }

                        MessageQueueVO messageQueueVO=new MessageQueueVO();
                        messageQueueVO.setType(type);//类型
                        messageQueueVO.setStatus("0");//状态 为发送
                        messageQueueVO.setMessageContent(FreeMarkerUtils.process(Content,map));//内容
                        messageQueueVO.setDestination("1".equals(type)?parentVO.getWeChatUser().getOpenId():parentVO.getPhone());//接收人
                        messageQueueVO.setAddTime(new Timestamp(new Date().getTime()).toString());
                        messageQueueVO.setSendTime(new Timestamp(new Date().getTime()).toString());
                        messageQueueService.update(messageQueueVO);

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TemplateException e) {
                    e.printStackTrace();
                } catch (NullPointerException e){
                    System.out.println("数据错误，可能是学生没有关联家长");
                } catch (Exception e){
                    e.printStackTrace();
                    //其他错误
                }
            }
        }else{
            //非规则数据  异常提示

        }

        {//添加日志记录
            MessageRecordVO messageRecordVO=new MessageRecordVO();
            messageRecordVO.setSendTime(new Timestamp(new Date().getTime()).toString());
            messageRecordVO.setMessageTemplate(messageTemplateVO);
            messageRecordService.update(messageRecordVO);
        }
        addMessage(redirectAttributes,"信息已经发送成功");*/
        return "redirect:" + GlobalSetting.getAdminPath() +"/"+ returnUrl;
    }

    /**
     * 根据Id拿到模版内容页面做回显
     * @param id
     * @param response
     */
    @RequestMapping("getContentById")
    @RequiresPermissions("business:messagetemplate:sendMassage")
    public void getContentById(String id,HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        String content = messageTemplateService.getContentById(id);
        response.getWriter().write(content);
    }

}